package com.tzy.rpc.register;/**
 * @description:
 * @Author HP
 * @create 2022/3/14 17:04
 */

import com.alibaba.nacos.api.exception.NacosException;
import com.google.common.collect.Lists;
import com.google.common.io.CharStreams;
import com.tzy.rpc.enumeration.RpcError;
import com.tzy.rpc.exception.RpcException;
import com.tzy.rpc.util.NacosUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.io.InputStreamReader;
import java.net.InetSocketAddress;

/**
 * @author HP
 * @create 2022-03-14 17:04
 * @desc 实现Nacos服务注册中心的实现类
 **/
public class NacosServiceRegistry implements ServiceRegistry{

    private static final Logger logger = LoggerFactory.getLogger(NacosServiceRegistry.class);
    private Jedis jedis=new Jedis("localhost", 6379);

    @Override
    public void register(String serviceName, InetSocketAddress inetSocketAddress) {
        try {
            //向Nacos注册服务
            NacosUtil.registerService(serviceName, inetSocketAddress);

            //服务的idx和总数记录到redis中
            try (
                    InputStreamReader reader = new InputStreamReader(NacosServiceRegistry.class.getResourceAsStream("/luaScript/registServiceInRedis.lua"));
            ){
                String script = CharStreams.toString(reader);
//                System.out.println(script);
                jedis.eval(script, Lists.newArrayList(serviceName+":idx",serviceName+":cnt"), Lists.newArrayList(""));
            }catch (Exception e){
                e.printStackTrace();
            }
        }catch (NacosException e) {
            logger.error("注册服务时有错误发生" + e);
            throw new RpcException(RpcError.REGISTER_SERVICE_FAILED);
        }
    }


}
